<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Todos</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.5.0/axios.js"></script>
</head>
<body>
    <h1>hello express website</h1>
    <input id="user" value="alice" />
    <button onclick="sendUser()">post to /api/user</button>
    <script>
        function sendUserByFetch() {
            const user = document.querySelector('#user').value
            fetch('/api/user', {
                method: 'POST',
                body: JSON.stringify({user: user, like: 'shopping'}),
                headers: {
                    'content-type': 'application/json'
                }
            })
        }


        async function sendUser() {
            const user = document.querySelector('#user').value
            const res = await axios({
                url: '/api/user',
                method: 'POST',
                data: {user: user, like: 'shopping'},
                headers: {
                    'content-type': 'application/json'
                }
            })
            console.log("🚀 ~ file: index.html:36 ~ sendUser ~ res:", res)

            
        }

        axios.interceptors.request.use((config) => {
            console.log("🚀 ~ file: index.html:42 ~ axios.interceptors.request.use ~ config:", config)
            if (config.data && localStorage.token) {
                console.log("🚀 ~ file: index.html:44 ~ axios.interceptors.request.use ~ config.data:", config.data)
                if (typeof config.data === 'string') {
                    config.data = Object.assign(JSON.parse(config.data), { token: localStorage.token});
                }
            }
            return config
        }, (error) => {
            console.log("🚀 ~ file: index.html:45 ~ axios.interceptors.request.use ~ error:", error)
            return Promise.reject(error);
        })

        axios.interceptors.response.use((res)=> {
            console.log("🚀 ~ file: index.html:50 ~ axios.interceptors.reponse.use ~ res:", res)
            return res
        }, async (error) => {
            console.log("🚀 ~ file: index.html:53 ~ axios.interceptors.reponse.use ~ error:", error)
            if (error.response.status === 401) {
                // replay            
                await new Promise(resolve => setTimeout(resolve, 3000, true));
                return axios(error.config)
            }
            
            return Promise.reject(error);
        })


        
    </script>
</body>
</html>